package com.itheima;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 测试读取表格
 */
public class ReadXSLS {
    public static void main(String[] args) throws IOException {
        //有null值得演示
        XSSFWorkbook workbook = new XSSFWorkbook("src\\main\\resources\\read_right.xlsx");

        //有错误数据类型的演示
//        XSSFWorkbook workbook = new XSSFWorkbook("src\\main\\resources\\read_wrong.xlsx");

        XSSFSheet sheet = workbook.getSheetAt(0);

        if (sheet == null) return;

        List<Student> list = new ArrayList<>();

        int lastRowNum = sheet.getLastRowNum();


        for (int i = 1; i <= lastRowNum; i++) {

            XSSFRow row = sheet.getRow(i);
            if (row != null) {

                short lastCellNum = row.getLastCellNum();

                System.out.println("第"+i+"行有效单元格个数 = " + lastCellNum);
                List<String> temp = new ArrayList<>();

                int wrong=-1;
                for (int j = 0; j <= lastCellNum; j++) {
                    XSSFCell cell = row.getCell(j);
                    if (cell != null) {
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        temp.add(cell.getStringCellValue());
                    }
                    wrong = j;
                }

                Student student = null;

                try {
                    student = new Student(
                            temp.size() >= 1 ? temp.get(0) : null,
                            temp.size() >= 2 ? Integer.parseInt(temp.get(1)) : null,
                            temp.size() >= 3 ? temp.get(2) : null,
                            temp.size() >= 4 ? temp.get(3) : null
                    );
                } catch (NumberFormatException e) {
                    System.out.println("数据类型错误,错误行数为第"+i+"行,第"+wrong+"个单元格");
                    return;
                }

                list.add(student);
            }

        }


        System.out.println("----------------------");


        for (Student student : list) {
            System.out.println(student);
        }


    }
}
//该行有效单元格个数 lastCellNum = 4
//该行有效单元格个数 lastCellNum = 1
//该行有效单元格个数 lastCellNum = 4
//Student{name='张三', age='23', id='001', address='重庆'}
//Student{name='李四', age='null', id='null', address='null'}
//Student{name='王麻子', age='25', id='003', address='上海'}
